package com.maben.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理权限不足的请求：返回 403 错误
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        // 设置响应格式为 JSON
        response.setContentType("application/json;charset=UTF-8");
        // 设置状态码 403（禁止访问）
        response.setStatus(HttpStatus.FORBIDDEN.value());

        // 构建返回的错误信息
        Map<String, Object> error = new HashMap<>();
        error.put("code", 403);
        error.put("msg", "没有访问权限");

        // 转为 JSON 写入响应
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(error));
    }
}